<template>
  <div class="watch-history-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <el-icon class="title-icon"><Clock /></el-icon>
          观看历史
        </h1>
        <p class="page-subtitle">记录您的视频观看足迹</p>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ watchHistory.length }}</div>
            <div class="stat-label">观看记录</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ totalWatchTime }}</div>
            <div class="stat-label">总观看时长</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon><Calendar /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ todayWatched }}</div>
            <div class="stat-label">今日观看</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon><Calendar /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ weeklyWatched }}</div>
            <div class="stat-label">本周观看</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选和排序 -->
    <div class="filter-section">
      <div class="filter-container">
        <div class="filter-group">
          <el-select v-model="selectedPeriod" placeholder="选择时间段" size="large">
            <el-option label="全部时间" value="all" />
            <el-option label="今天" value="today" />
            <el-option label="本周" value="week" />
            <el-option label="本月" value="month" />
            <el-option label="今年" value="year" />
          </el-select>
        </div>
        <div class="filter-group">
          <el-select v-model="sortBy" placeholder="排序方式" size="large">
            <el-option label="最近观看" value="recent" />
            <el-option label="观看时长" value="duration" />
            <el-option label="视频标题" value="title" />
            <el-option label="观看次数" value="count" />
          </el-select>
        </div>
        <div class="filter-group">
          <el-button-group>
            <el-button 
              :type="viewMode === 'grid' ? 'primary' : 'default'" 
              @click="viewMode = 'grid'"
              size="large"
            >
              <el-icon><Grid /></el-icon>
              网格
            </el-button>
            <el-button 
              :type="viewMode === 'list' ? 'primary' : 'default'" 
              @click="viewMode = 'list'"
              size="large"
            >
              <el-icon><List /></el-icon>
              列表
            </el-button>
          </el-button-group>
        </div>
        <div class="filter-group">
          <el-button type="danger" @click="clearHistory" size="large">
            <el-icon><Delete /></el-icon>
            清空历史
          </el-button>
        </div>
      </div>
    </div>

    <!-- 观看历史内容 -->
    <div class="content-section">
      <div class="history-container" :class="viewMode">
        <div 
          v-for="item in filteredHistory" 
          :key="item.id" 
          class="history-card"
          @click="goToDetail(item.video_id)"
        >
          <div class="video-thumbnail">
            <img :src="item.thumbnail" :alt="item.title" />
            <div class="video-overlay">
              <el-icon class="play-icon"><CaretRight /></el-icon>
            </div>
            <div class="video-duration">{{ item.duration }}</div>
            <div class="watch-progress">
              <div class="progress-bar" :style="{ width: item.watch_progress + '%' }"></div>
            </div>
          </div>
          <div class="video-info">
            <h3 class="video-title">{{ item.title }}</h3>
            <p class="video-description">{{ item.description }}</p>
            <div class="video-meta">
              <div class="meta-left">
                <span class="watch-time">
                  <el-icon><Clock /></el-icon>
                  {{ formatWatchTime(item.watch_time) }}
                </span>
                <span class="watch-count">
                  <el-icon><View /></el-icon>
                  {{ item.watch_count }} 次
                </span>
              </div>
              <div class="meta-right">
                <span class="date">{{ formatDate(item.last_watched) }}</span>
              </div>
            </div>
            <div class="history-actions">
              <el-button size="small" @click.stop="continueWatching(item)">
                <el-icon><CaretRight /></el-icon>
                继续观看
              </el-button>
              <el-button size="small" @click.stop="removeFromHistory(item)">
                <el-icon><Delete /></el-icon>
                移除
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="filteredHistory.length === 0" class="empty-state">
        <el-empty description="暂无观看历史">
          <el-button type="primary" @click="goToHome">
            <el-icon><HomeFilled /></el-icon>
            去首页看看
          </el-button>
        </el-empty>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElIcon, ElSelect, ElOption, ElButton, ElButtonGroup, ElEmpty, ElMessage, ElMessageBox } from 'element-plus'
import { 
  Clock, Calendar, Grid, List, Delete, 
  CaretRight, View, HomeFilled 
} from '@element-plus/icons-vue'
import api from '@/utils/axios'

const router = useRouter()

// 响应式数据
const selectedPeriod = ref('all')
const sortBy = ref('recent')
const viewMode = ref('grid')
const loading = ref(false)

// 观看历史数据
const watchHistory = ref([])

// 计算属性
const filteredHistory = computed(() => {
  let history = watchHistory.value
  
  // 按时间段筛选
  if (selectedPeriod.value !== 'all') {
    const now = new Date()
    const filterDate = new Date()
    
    switch (selectedPeriod.value) {
      case 'today':
        filterDate.setHours(0, 0, 0, 0)
        break
      case 'week':
        filterDate.setDate(now.getDate() - 7)
        break
      case 'month':
        filterDate.setMonth(now.getMonth() - 1)
        break
      case 'year':
        filterDate.setFullYear(now.getFullYear() - 1)
        break
    }
    
    history = history.filter(item => 
      new Date(item.last_watched) >= filterDate
    )
  }
  
  // 排序
  return history.sort((a, b) => {
    switch (sortBy.value) {
      case 'recent':
        return new Date(b.last_watched) - new Date(a.last_watched)
      case 'duration':
        return parseDuration(b.watch_time) - parseDuration(a.watch_time)
      case 'title':
        return a.title.localeCompare(b.title)
      case 'count':
        return b.watch_count - a.watch_count
      default:
        return 0
    }
  })
})

const totalWatchTime = computed(() => {
  const totalMinutes = watchHistory.value.reduce((sum, item) => {
    return sum + parseDuration(item.watch_time)
  }, 0)
  
  const hours = Math.floor(totalMinutes / 60)
  const minutes = totalMinutes % 60
  return `${hours}小时${minutes}分钟`
})

const todayWatched = computed(() => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return watchHistory.value.filter(item => 
    new Date(item.last_watched) >= today
  ).length
})

const weeklyWatched = computed(() => {
  const oneWeekAgo = new Date()
  oneWeekAgo.setDate(oneWeekAgo.getDate() - 7)
  return watchHistory.value.filter(item => 
    new Date(item.last_watched) >= oneWeekAgo
  ).length
})

// 方法
const parseDuration = (duration) => {
  if (!duration) return 0
  const parts = duration.split(':')
  if (parts.length === 3) {
    return parseInt(parts[0]) * 60 + parseInt(parts[1])
  } else if (parts.length === 2) {
    return parseInt(parts[0]) * 60 + parseInt(parts[1])
  }
  return 0
}

const formatWatchTime = (time) => {
  if (!time) return '0分钟'
  const minutes = parseDuration(time)
  const hours = Math.floor(minutes / 60)
  const mins = minutes % 60
  
  if (hours > 0) {
    return `${hours}小时${mins}分钟`
  }
  return `${mins}分钟`
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

const goToDetail = (videoId) => {
  router.push(`/detail/${videoId}`)
}

const goToHome = () => {
  router.push('/home')
}

const continueWatching = (item) => {
  router.push(`/player/${item.video_id}?t=${item.watch_progress}`)
}

const removeFromHistory = async (item) => {
  try {
    await api.delete(`/user/watch-history/${item.id}`)
    
    const index = watchHistory.value.findIndex(h => h.id === item.id)
    if (index > -1) {
      watchHistory.value.splice(index, 1)
      ElMessage.success('已从观看历史中移除')
    }
  } catch (error) {
    console.error('移除观看历史失败:', error)
    ElMessage.error('移除观看历史失败')
  }
}

const clearHistory = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有观看历史吗？此操作不可恢复。',
      '确认清空',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await api.delete('/user/watch-history')
    watchHistory.value = []
    ElMessage.success('观看历史已清空')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空观看历史失败:', error)
      ElMessage.error('清空观看历史失败')
    }
  }
}

// 加载观看历史
const loadWatchHistory = async () => {
  try {
    loading.value = true
    const response = await api.get('/user/watch-history')
    if (response.success) {
      watchHistory.value = response.data
    }
  } catch (error) {
    console.error('加载观看历史失败:', error)
    // 使用示例数据
    watchHistory.value = [
      {
        id: 1,
        video_id: 1,
        title: '复仇者联盟：终局之战',
        description: '漫威超级英雄的史诗级终章',
        thumbnail: '/images/videos/video1.jpg',
        duration: '03:01:00',
        watch_time: '01:30:00',
        watch_progress: 50,
        watch_count: 3,
        last_watched: new Date(Date.now() - 1000 * 60 * 60 * 2)
      },
      {
        id: 2,
        video_id: 2,
        title: '权力的游戏 第八季',
        description: '史诗奇幻剧集的最终季',
        thumbnail: '/images/videos/video2.jpg',
        duration: '01:20:00',
        watch_time: '00:45:00',
        watch_progress: 75,
        watch_count: 2,
        last_watched: new Date(Date.now() - 1000 * 60 * 60 * 6)
      },
      {
        id: 3,
        video_id: 3,
        title: '精彩影视剧集',
        description: '精选影视内容推荐',
        thumbnail: '/images/videos/微信图片_20251027113113.jpg',
        duration: '01:45:00',
        watch_time: '01:45:00',
        watch_progress: 100,
        watch_count: 1,
        last_watched: new Date(Date.now() - 1000 * 60 * 60 * 24)
      },
      {
        id: 4,
        video_id: 4,
        title: '推荐视频1',
        description: '热门推荐内容',
        thumbnail: '/images/videos/微信图片_20251027113117.jpg',
        duration: '01:20:00',
        watch_time: '00:20:00',
        watch_progress: 25,
        watch_count: 1,
        last_watched: new Date(Date.now() - 1000 * 60 * 60 * 24 * 2)
      }
    ]
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadWatchHistory()
})
</script>

<style scoped>
.watch-history-page {
  min-height: 100vh;
  background: #f9fafb;
}

.page-header {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  padding: 60px 0;
  color: white;
  text-align: center;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-title {
  font-size: 2.5rem;
  margin: 0 0 10px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15px;
}

.title-icon {
  font-size: 2.5rem;
}

.page-subtitle {
  font-size: 1.1rem;
  opacity: 0.9;
  margin: 0;
}

.stats-section {
  background: white;
  padding: 40px 0;
  border-bottom: 1px solid #e5e7eb;
}

.stats-grid {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-card {
  background: #f8fafc;
  border-radius: 12px;
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 16px;
  transition: all 0.3s ease;
}

.stat-card:hover {
  background: #e2e8f0;
  transform: translateY(-2px);
}

.stat-icon {
  width: 48px;
  height: 48px;
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 1.8rem;
  font-weight: bold;
  color: #1f2937;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 0.9rem;
  color: #6b7280;
}

.filter-section {
  background: white;
  padding: 30px 0;
  border-bottom: 1px solid #e5e7eb;
}

.filter-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  gap: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-group {
  display: flex;
  align-items: center;
}

.content-section {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
}

.history-container.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
}

.history-container.list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.history-container.list .history-card {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 16px;
}

.history-container.list .video-thumbnail {
  width: 200px;
  height: 120px;
  flex-shrink: 0;
}

.history-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
}

.history-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.video-thumbnail {
  position: relative;
  width: 100%;
  height: 180px;
  overflow: hidden;
}

.video-thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.history-card:hover .video-overlay {
  opacity: 1;
}

.play-icon {
  font-size: 48px;
  color: white;
}

.video-duration {
  position: absolute;
  bottom: 8px;
  right: 8px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.watch-progress {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: rgba(255, 255, 255, 0.3);
}

.progress-bar {
  height: 100%;
  background: #10b981;
  transition: width 0.3s ease;
}

.video-info {
  padding: 20px;
}

.video-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 8px 0;
  line-height: 1.4;
}

.video-description {
  font-size: 0.9rem;
  color: #6b7280;
  margin: 0 0 12px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.video-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.meta-left {
  display: flex;
  gap: 16px;
}

.meta-left span {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 0.85rem;
  color: #9ca3af;
}

.meta-right .date {
  font-size: 0.85rem;
  color: #9ca3af;
}

.history-actions {
  display: flex;
  gap: 8px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-title {
    font-size: 2rem;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .filter-container {
    flex-direction: column;
    align-items: stretch;
  }
  
  .history-container.grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  }
  
  .history-container.list .history-card {
    flex-direction: column;
  }
  
  .history-container.list .video-thumbnail {
    width: 100%;
    height: 160px;
  }
}

@media (max-width: 480px) {
  .page-title {
    font-size: 1.5rem;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .history-container.grid {
    grid-template-columns: 1fr;
  }
}
</style>